package com.rongji.egov.fileupload.rjfile;

import com.rongji.egov.fileupload.RjFileProperties;
import com.rongji.egov.fileupload.server.FileNettyServer;
import com.rongji.egov.fileupload.utils.FileConfig;
import io.netty.channel.ChannelFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class RjfileBootstrapRunner implements ApplicationRunner, ApplicationListener<ContextClosedEvent>, ApplicationContextAware {
    private static final Logger logger = LoggerFactory.getLogger(RjfileBootstrapRunner.class);
    private static ApplicationContext applicationContext;
    public static FileNettyServer fileNettyServer;

    @Resource
    RjFileProperties prop;

    @Override
    public void run(ApplicationArguments args) {
        //启动服务
        logger.info("fileServer 服务启动........");
        FileConfig config = new FileConfig.Builder()
                .port(prop.getPort()).path(prop.getPath())
                .build();

        logger.info("FileNettyServer配置{}", config);
        fileNettyServer = new FileNettyServer(config, 4, 16);
        try {
            ChannelFuture future = fileNettyServer.bing().sync();
            if(future.isSuccess()){
                String msg = "服务启动成功";
                logger.info(msg);
                System.out.println();
            } else {
                String msg = "服务启动失败";
                logger.error(msg);
                System.out.println(msg);
            }

        } catch (Exception e) {
            logger.error("服务启动异常！", e);
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void onApplicationEvent(ContextClosedEvent event) {
        fileNettyServer.destroy();
        logger.info("fileServer 服务停止...........");
    }
}
